<template>
  <div class="block">
    <el-button type="primary" style="margin: 5px" @click="addNote">新建笔记</el-button>
    <el-timeline>
      <el-timeline-item v-for="(note,index) of noteList" :key="index" :timestamp="note.created" placement="top">
        <el-card style="width: 100%">
          <p>{{ note.content }}</p>
          <span>
            <el-button style="float: right;margin: 10px" type="primary" icon="el-icon-edit" circle @click="editNote(note)"></el-button>
          </span>
          <span>
            <el-button style="float: right;margin: 10px" type="danger" icon="el-icon-delete" circle @click="removeNote(note.id)"></el-button>
          </span>
        </el-card>
      </el-timeline-item>
    </el-timeline>

    <el-dialog :visible.sync="dialogVisible" :title="dialogType==='edit'?'修改':'创建'">
      <el-form :model="note" label-width="80px" label-position="left">
        <el-form-item label="内容">
          <el-input v-model="note.content" placeholder="内容"/>
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="confirm">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addNote, getMyNote, modifyNote, removeNote } from '@/api/note'
const defaultNote = {
  id: ''
}

export default {
  data() {
    return {
      note: Object.assign({}, defaultNote),
      noteList: [],
      dialogVisible: false,
      dialogType: 'new',
    }
  },
  created() {
    this.getNotes()
  },
  methods: {
    async getNotes() {
      const res = await getMyNote()
      this.noteList = res.data
    },
    addNote() {
      this.dialogType = 'new'
      this.note = Object.assign({}, defaultNote)
      this.dialogVisible = true
    },
    async editNote(note) {
      this.dialogType = 'edit'
      this.dialogVisible = true
      this.note = note
    },
    async confirm() {
      if ('edit' === this.dialogType) {
        await modifyNote(this.note.id, this.note)
      }else {
        await addNote(this.note)
      }
      await this.getNotes()
      this.dialogVisible = false
      this.$notify({
        title: 'Success',
        dangerouslyUseHTMLString: true,
        message: '操作成功',
        type: 'success'
      })
    },
    async removeNote(id) {
      await removeNote(id)
      await this.getNotes()
    }
  }
}
</script>
